package com.taotao.sso.service;

import java.io.IOException;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.service.RedisService;
import com.taotao.sso.bean.User;
import com.taotao.sso.mapper.UserMapper;
import com.taotao.sso.pojo.TbUser;
import com.taotao.sso.service.IUserService;

@Service
public class UserService{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RedisService redisService;
	
	@Autowired
	private IUserService userService;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	public Boolean check(String param, Integer type) {
		TbUser user = new TbUser();
		switch (type) {
		case 1:
			user.setUsername(param);
			break;
		case 2:
			user.setPhone(param);
			break;
		case 3:
			user.setEmail(param);
			break;
		default:
			return null;
		}
		
		return this.userMapper.selectOne(user) == null;
	}
	
	 public Boolean saveUser(TbUser user) {
	        user.setId(null);
	        user.setCreated(new Date());
	        user.setUpdated(user.getCreated());

	        // 密码加密处理，使用MD5
	        user.setPassword(DigestUtils.md5Hex(user.getPassword()));

	        return this.userMapper.insert(user) == 1;
	    }
	 
	   public String doLogin(String username, String password) throws Exception {
	        TbUser record = new TbUser();
	        record.setUsername(username);
	        TbUser user = this.userMapper.selectOne(record);
	        if (null == user) {
	            // 用户不存在
	            return null;
	        }
	        // 判断密码是否相当
	        if (!StringUtils.equals(DigestUtils.md5Hex(password), user.getPassword())) {
	            return null;
	        }

	        // 登录成功
	        // 生成token
	        String token = DigestUtils.md5Hex(System.currentTimeMillis() + username);

	        // 将用户数据保存到Redis中  ---密码从安全性考虑上讲，应该剔除
	        //user.setPassword(null);//不用这么做，直接在转json中忽略这个字段即可
	        this.redisService.set("TOKEN_" + token, MAPPER.writeValueAsString(user), 1800);

	        return token;
	    }
	   
	   
	public User queryUserByToken(String token) {
		return userService.queryUserByToken(token);//调用Dubbo服务
	}

}
